﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MesDock.Entity;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Security.Cryptography;
using Time.Foramework;
namespace MesDock
{
    class ConnectWebService
    {
        private MESWebService.MainWebserviceClient mesWebService = new MESWebService.MainWebserviceClient();
        public bool WebService(DeviceData deviceData, out bool mesResult, out bool mesVerify, out string mesCode, out string mesResponse, out string webServiceSign)
        {
            //MD5d
            mesResult = false;
            mesVerify = true;
            mesResponse = "";
            webServiceSign = "";
            mesCode = "0";
            bool postException = false;
            JToken result, verify, code;
            JObject jObjResp = new JObject();
            StringBuilder sBuilder = new StringBuilder();
            sBuilder.Clear();
            sBuilder.Append(deviceData.AccessToken);
            sBuilder.Append("-");
            sBuilder.Append(deviceData.EquipmentID);
            sBuilder.Append("-");
            sBuilder.Append(deviceData.UserID);
            sBuilder.Append("-");
            sBuilder.Append(deviceData.Type);
            sBuilder.Append("-");
            sBuilder.Append(deviceData.Data);
            deviceData.Sign = GetMd5Hash(sBuilder.ToString());
            webServiceSign = deviceData.Sign;
            sBuilder.Append("-");
            sBuilder.Append(deviceData.Sign);
            string ErrorMessage = null;
            try
            {
                if (deviceData.Type != "verifya")
                {
                    Console.WriteLine("发送数据给MES：");
                    Console.WriteLine("eid:{0},uid:{1},type:{2},data:{3},sign:{4}", deviceData.EquipmentID,
                        deviceData.UserID, deviceData.Type, deviceData.Data, deviceData.Sign);
                }
                else
                {
                    Console.WriteLine("发送数据给MES：");
                    Console.WriteLine("eid:{0},uid:{1},type:{2},data:{3},sign:{4}", deviceData.EquipmentID,
                        deviceData.UserID, deviceData.Type, deviceData.Data[0], deviceData.Sign);
                }
                mesResponse = mesWebService.service(deviceData.EquipmentID, deviceData.UserID, deviceData.Type, deviceData.Data, deviceData.Sign);

                //响应超时（5秒）
                mesWebService.InnerChannel.OperationTimeout = new TimeSpan(0, 0, 5);
                Time.Foramework.ConfigOperate.PrintLog(deviceData.Type + ":" + mesResponse);
                Time.Foramework.ConfigOperate.PrintLog(deviceData.Type + ",EquipmentID:" + deviceData.EquipmentID + ",UserID:" + deviceData.UserID+ ",Type:" + deviceData.Type + ",Data:" + deviceData.Data + ",Sign:" + deviceData.Sign);
                Console.WriteLine("MESResponse：{0}", mesResponse);
            }
            catch (System.ServiceModel.CommunicationException e)
            {
                ErrorMessage = e.Message.ToString();
                postException = true;
            }
            catch (System.TimeoutException ee)
            {
                ErrorMessage = ee.Message.ToString();
                postException = true;
            }
            catch (System.Net.WebException eee)
            {
                ErrorMessage = eee.Message.ToString();
                postException = true;
            }
            catch (System.Exception ex)
            {
                ErrorMessage = ex.Message.ToString();
                postException = true;
            }
            Time.Foramework.ConfigOperate.PrintLog(deviceData.Type + ":" + ErrorMessage);
            //WebService返回处理：JSON
            //MES返回判断
            if (string.Equals(mesResponse, "") || postException)
            {
                return false;
            }
            try
            {
                jObjResp = (JObject)JsonConvert.DeserializeObject(mesResponse);
                if (jObjResp.TryGetValue("result", out result))
                {
                    mesResult = (bool)result;
                }
                if (jObjResp.TryGetValue(deviceData.Type, out verify))
                {
                    mesVerify = (bool)verify;
                }
                if (jObjResp.TryGetValue("code", out code))
                {
                    mesCode = (string)code;
                }
            }
            catch (Exception)
            {
                throw;
            }
            return true;
        }
        /// <summary>
        /// 获取验证
        /// </summary>
        /// <param name="strInput"></param>
        /// <returns></returns>
        private string GetMd5Hash(string strInput)
        {
            MD5 md5Hasher = MD5.Create();
            byte[] btData = md5Hasher.ComputeHash(Encoding.Default.GetBytes(strInput));
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < btData.Length; i++)
            {
                sBuilder.Append(btData[i].ToString("x2"));
            }
            return sBuilder.ToString();
        }
    }
}

